package com.cnblogs.leizia.crm.configuration.filter;

import com.cnblogs.leizia.crm.settings.domain.User;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author leizi
 * @create 2021-02-15 22:02
 */
public class LoginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        User user = (User) req.getSession().getAttribute("user");
        // 获取当前工程路径
        String contextPath = req.getContextPath();
        // 判断用户是否登录，未登录重定向到登录页
        if (null == user) {
            HttpServletResponse resp = (HttpServletResponse) response;
            resp.sendRedirect(contextPath + "/login.jsp");
        } else {
            chain.doFilter(request, response);
        }

    }

    @Override
    public void destroy() {

    }
}
